<?php

namespace mbilling\BillingBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;

use mbilling\BillingBundle\Model\UsersBillsModel;
use mbilling\BillingBundle\Model\OrdersModel;
use mbilling\BillingBundle\Model\OrdersSharedModel;
use mbilling\BillingBundle\Model\OrdersVpsModel;
use mbilling\BillingBundle\Model\OrdersSharedTarifModel;
use mbilling\BillingBundle\Model\OrdersVpsTarifModel;
use mbilling\BillingBundle\Model\UsersTransactionsModel;
use mbilling\BillingBundle\Model\UsersTotalTransactionsModel;
use mbilling\BillingBundle\Model\UsersAdminLogsModel;
use mbilling\BillingBundle\Model\UsersLogsModel;
use mbilling\BillingBundle\Model\UsersModel;
use mbilling\BillingBundle\Model\UsersBillsSourcesModel;
use mbilling\BillingBundle\Model\DomainsZonesModel;
use mbilling\BillingBundle\Model\OrdersTarifsTermsModel;
use mbilling\BillingBundle\Model\OrdersIpTableModel;
use mbilling\BillingBundle\Model\OrdersIpModel;
use mbilling\BillingBundle\Model\BonusesModel;
use mbilling\BillingBundle\Model\BonusesTableModel;
use mbilling\BillingBundle\Model\DomainsModel;
use mbilling\BillingBundle\Model\DomainsDnsModel;
use mbilling\BillingBundle\Model\UsersBillsSumsModel;
use mbilling\BillingBundle\Entity\usersBills;
use mbilling\BillingBundle\Entity\usersTransactions;
use mbilling\BillingBundle\Entity\usersAdminLogs;
use mbilling\BillingBundle\Entity\usersLogs;
use mbilling\BillingBundle\Entity\bonusesTable;

use mbilling\BillingBundle\Form\UsersBillsForm;

use Symfony\Component\Security\Acl\Permission\MaskBuilder;

class UsersBillsController extends Controller
{
    public function indexAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $bill_model = new UsersBillsModel($em);
        $order_model = new OrdersModel($em);
        $orderVps_model = new OrdersVpsModel($em);
        $orderShared_model = new OrdersSharedModel($em);
        $orderSharedTarif_model = new OrdersSharedTarifModel($em);
        $orderVpsTarif_model = new OrdersVpsTarifModel($em);
        $user_model = new UsersModel($em);
        //$zone_model = new DomainsZonesModel($em);
        $tarifTerms_model = new OrdersTarifsTermsModel($em);
        $domain_model = new DomainsModel($em);
        
        $domains = $domain_model->findAll();
        $domain_string = array();
        foreach($domains as $domain)
        {
            $domain_string[$domain->getId()] = $domain->getName();
        }

        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();

        $parameters = array();
        if ($userCurrent->isAdmin())
        {
            if ($this->get('session')->get('user'))
                $bills = $bill_model->findByUserId($this->get('session')->get('user')->getId());
            else
                $bills = $bill_model->findAll();
        }
        else
            $bills = $bill_model->findByUserId($userCurrent->getId());
        
        foreach($bills as $bill)
        {
            $zone = array();
            $order = $order_model->findByPK($bill->getOrderId());
            if (isset($order))
            {
                if ($order->isShared())
                {
                    $orderAdv = $orderShared_model->findByOrderId($order->getId());
                    $orderAdvTarif = $orderSharedTarif_model->findByPK($orderAdv->getSharedTarif());
                    /*$check_domain = $this->get('check_domain');
                    $check_domain->init($orderAdv->getDomain());
                    $zone = $zone_model->findByName($check_domain->get_tld());

                    $period = $bill->getMoney() / $orderAdvTarif->getCost() / 30;
                    if ($bill->getMoney() % $orderAdvTarif->getCost() % 30)
                        $period = ($bill->getMoney() - $zone->getRegCost()) / $orderAdvTarif->getCost() / 30;*/
                }
                elseif ($order->isVps())
                {
                    $orderAdv = $orderVps_model->findByOrderId($order->getId());
                    $orderAdvTarif = $orderVpsTarif_model->findByPK($orderAdv->getVpsTarif());
                    //$period = $bill->getMoney() / $orderAdvTarif->getCost() / 30;
                }
                $user = $user_model->findByPK($order->getUserId());
                array_push($parameters, array('order'    => $order,
                                              'orderAdv' => $orderAdv,
                                              'tarif'    => $orderAdvTarif,
                                              'bill'     => $bill,
                                              'user'     => $user,
                                              'hash'     => md5($bill->getId().$user->getSalt())));
                                              //'period'   => $period
            }
            else
            {
                $user = $user_model->findByPK($bill->getUserId());
                array_push($parameters, array('bill'     => $bill,
                                              'user'     => $user,
                                              'hash'     => md5($bill->getId().$user->getSalt())));
            }
        }
        if ($userCurrent->isAdmin())
        {
            if ($this->get('session')->get('user'))
                return $this->render('BillingBundle:UsersBills:user_index.html.twig', array('parameters' => $parameters, 'domains' => $domain_string));
            else
                return $this->render('BillingBundle:UsersBills:admin_index.html.twig', array('parameters' => $parameters, 'domains' => $domain_string));
        }
        else
            return $this->render('BillingBundle:UsersBills:user_index.html.twig', array('parameters' => $parameters, 'domains' => $domain_string));
    }
    public function differentAction($hash)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $bill_model = new UsersBillsModel($em);
        $order_model = new OrdersModel($em);
        $orderVps_model = new OrdersVpsModel($em);
        $orderShared_model = new OrdersSharedModel($em);
        $orderSharedTarif_model = new OrdersSharedTarifModel($em);
        $orderVpsTarif_model = new OrdersVpsTarifModel($em);
        $user_model = new UsersModel($em);
        
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $userCurrent = $user_model->findByPK($this->get('session')->get('user')->getId());
        
        $parameters = array();
        $bills = $bill_model->findAll();
        $bill = NULL;
        foreach($bills as $b)
        {
            if ($hash == md5($b->getId().$userCurrent->getSalt()))
                $bill = $b;
        }
        if (!$bill)
            return new Response('false');

        $acl = $this->get('acl');
        $acl->checkPermissions($bill, 'VIEW');
 
        $order = $order_model->findByPK($bill->getOrderId());
        if ($order->isShared())
        {
            $orderAdv = $orderShared_model->findByOrderId($order->getId());
            $orderAdvTarif = $orderSharedTarif_model->findByPK($orderAdv->getSharedTarif());
        }
        elseif ($order->isVps())
        {
            $orderAdv = $orderVps_model->findByOrderId($order->getId());
            $orderAdvTarif = $orderVpsTarif_model->findByPK($orderAdv->getVpsTarif());
        }
        $user = $user_model->findByPK($order->getUserId());
        array_push($parameters, array('order'       => $order,
                                      'orderAdv'    => $orderAdv,
                                      'tarif'       => $orderAdvTarif,
                                      'bill'        => $bill,
                                      'user'        => $user));

        if ($userCurrent->isAdmin())
        {
            if ($this->get('session')->get('user'))
                return $this->render('BillingBundle:UsersBills:user_index.html.twig', array('parameters' => $parameters));
            else
                return $this->render('BillingBundle:UsersBills:admin_index.html.twig', array('parameters' => $parameters));
        }
        else
            return $this->render('BillingBundle:UsersBills:user_index.html.twig', array('parameters' => $parameters));
    }
    public function showSourcesAction($hash)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $userCurrent = $user_model->findByPK($this->get('session')->get('user')->getId());
        
        $order_model = new OrdersModel($em);
        $orderShared_model = new OrdersSharedModel($em);
        $orderSharedTarif_model = new OrdersSharedTarifModel($em);
        $source_model = new UsersBillsSourcesModel($em);
        $domain_model = new DomainsModel($em);
        $user_model = new UsersModel($em);
        $totalTransaction_model = new UsersTotalTransactionsModel($em);
        $zone_model = new DomainsZonesModel($em);
        $bonus_model = new BonusesModel($em);
        $usersBillsSums_model = new UsersBillsSumsModel($em);
        $transaction_model = new UsersTransactionsModel($em);
        $bill_model = new UsersBillsModel($em);

        $bills = $bill_model->findAll();
        $bill = NULL;
        foreach($bills as $b)
        {
            if ($hash == md5($b->getId().$userCurrent->getSalt()))
                $bill = $b;
        }
        if (!$bill)
            return new Response('false');
        
        $acl = $this->get('acl');
        $acl->checkPermissions($bill, 'VIEW');
        
        $dir=opendir(dirName('../'.basename(__FILE__)).'/vendor/mpanel/classes/Bonuses/');
        $file_string = array();
        while ($file = readdir($dir))
        {
            if (in_array($file,array('.','..')))
                continue;
            $expl=explode('.', $file);
            $expl_size=sizeof($expl);
            if (mb_strtolower($expl[$expl_size-1],'UTF-8') != 'php')
                continue;
            $file_len = sizeof($file_string);
            $file_string[$file_len] = $file;
        }
        closedir($dir);
        array_multisort($file_string);
        $names = array();
        $coupons = array();
        foreach($file_string as $coupon)
        {
            $expl=explode('.', $coupon);
            $class_name = $expl['0'];
            $class_name = 'Bonuses_'.$class_name;
            $check_domain = $this->get('check_domain');
            $class = $class_name::newInstance(NULL, NULL, NULL, $check_domain, $em);
            array_push($names, $class_name);
            array_push($coupons, $class->getTitle());
        }
        
        $bonuses = $bonus_model->findAll();
        $usersBillsSums = $usersBillsSums_model->findAllActive();
        $bonuses_string = array();
        $coupons_string = array();
        foreach($usersBillsSums as $usersBillsSum)
        {
            foreach($bonuses as $bonus)
            {
                if (($bonus->getIsActive()) && ($bonus->getSum() <= $usersBillsSum->getSumm()))
                {
                    if (!$bonus->getIsPercent())
                        $bonuses_string[$usersBillsSum->getSumm()] = $bonus->getAdding();
                    else
                        $bonuses_string[$usersBillsSum->getSumm()] = ($usersBillsSum->getSumm() * $bonus->getAdding() / 100);
                    if ($bonus->getCoupon() != 'no')
                    {
                        foreach($names as $key => $name)
                        {
                            if ($name == $bonus->getCoupon())
                                $coupons_string[$usersBillsSum->getSumm()] = '+'.$coupons[$key].'('.$bonus->getCouponNum().' штук)';
                        }
                    }
                }
            }
        }

        $checkbox_to_render = array();
        //$checked = array();
        $c = array();
        $checkbox_count = 0;
        foreach($file_string as $coupon)
        {
            $expl=explode('.', $coupon);
            $class = $expl['0'];
            $class = 'Bonuses_'.$class;
            $domain = $domain_model->FindByPK($bill->getDomainId());
            $check_domain = $this->get('check_domain');
            $c[$class] = $class::newInstance($domain, $userCurrent, $bill, $check_domain, $em);
            if ($c[$class]->cani())
            {
                $checkbox_to_render[$class]['state'] = 1;
                $checkbox_to_render[$class]['title'] = $c[$class]->getTitle();
                $checkbox_count++;
            }
            else
            {
                $checkbox_to_render[$class]['state'] = 0;
                $checkbox_to_render[$class]['title'] = $c[$class]->getTitle();
            }
            //$checked[$class] = 0;
        }
        
        $totalTransaction = $totalTransaction_model->findByUserId($userCurrent->getId());
        //$sources = $source_model->findAll();
        if ($bill->getOrderId())
        {
            $order= $order_model->findByPK($bill->getOrderId());
            if ($order->getType() == '1')
            {
                $orderShared = $orderShared_model->findByOrderId($order->getId());
                $orderSharedTarif = $orderSharedTarif_model->findByPK($orderShared->getSharedTarif());
            }
        }
        else
        {
            $order = NULL;
            $orderShared = NULL;
            $orderSharedTarif = NULL;
        }
        if ($bill->getDomainId())
        {
            $check_domain = $this->get('check_domain');
            $domain = $domain_model->FindByPK($bill->getDomainId());
            $check_domain->init($domain->getName());
            $zone = $zone_model->findByName($check_domain->get_tld());
        }
        else
        {
            $zone = NULL;
        }
        
        $summ = 0;
        $transactions = $transaction_model->findByUserId($userCurrent->getId());
        foreach($transactions as $transaction)
        {
            if ($transaction->getIsRegular())
            {
                if ($transaction->getIsAdding())
                {
                    $summ -= $transaction->getMoney();
                }
                else
                {
                    $summ += $transaction->getMoney();
                }
            }
        }
        $days_string = array();
        foreach($usersBillsSums as $usersBillsSum)
        {
            $consumption = $summ;
            if ($orderSharedTarif)
            {
                $consumption += $orderSharedTarif->getCost();
            }
            
            $all_money = $totalTransaction->getMoney() + $usersBillsSum->getSumm();
            if (array_key_exists((int)$usersBillsSum->getSumm(), $bonuses_string))
            {
                $all_money += (int)$bonuses_string[$usersBillsSum->getSumm()];
            }
            if ($orderSharedTarif)
            {
                if ($zone)
                    $all_money -= $zone->getRegCost();
            }
            else if ($zone)
            {
                if ($bill->getType() == '4')
                    $all_money -= $zone->getRegCost();
                else if ($bill->getType() == '5')
                    $all_money -= $zone->getExtCost();
            }
            if ($all_money < $consumption)
                $days_string[$usersBillsSum->getSumm()] = '0';
            else if ($consumption != 0)
                $days_string[$usersBillsSum->getSumm()] = floor(($all_money) / $consumption);
            else
                $days_string[$usersBillsSum->getSumm()] = 'бесконечно';
        }
        /*if (isset($_POST['add_bill']))
        {
            foreach ($checkbox_to_render as $key => $checkbox)
            {
                if (isset($_POST[$key]))
                {
                    $checked[$key] = '1';
                    $c[$key]->action();
                }
                else
                    $checked[$key] = '0';
            }
            return new RedirectResponse($this->generateUrl('users_bills_show'));
        }*/
        return $this->render('BillingBundle:UsersBills:user_choose_source.html.twig', 
                array('bill' => $bill, 
                      //'sources' => $sources, 
                      'checkboxes' => $checkbox_to_render, 
                      'totalTransaction' => $totalTransaction, 
                      'orderSharedTarif' => $orderSharedTarif, 
                      'zone' => $zone, 
                      'usersBillsSums' => $usersBillsSums, 
                      'bonuses' => $bonuses_string, 
                      'coupons' => $coupons_string, 
                      'checkbox_count' => $checkbox_count,
                      'days' => $days_string,
                      'hash' => $hash));//, 'checked' => $checked));
    }
    public function showPaySystemsAction()
    {
        $cost = $_POST['cost'];
        $hash = $_POST['hash'];
        //$cost = 1340;
        //$hash = '841f8b2d429421ce7cca76c0eb80555a';
        $em = $this->get('doctrine.orm.entity_manager');
        $bill_model = new UsersBillsModel($em);
        $bills = $bill_model->findAll();
        
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $userCurrent = $user_model->findByPK($this->get('session')->get('user')->getId());
        $bill = NULL;
        foreach($bills as $b)
        {
            if ($hash == md5($b->getId().$userCurrent->getSalt()))
                $bill = $b;
        }
        if (!$bill)
            return new Response('false');
        
        $source_model = new UsersBillsSourcesModel($em);
        $sources = $source_model->findAll();
        $html = '';
        foreach($sources as $source)
        {
            $expl=explode('.', $source->getFile());
            $class = $expl['0'];
            $class = 'PaySystems_'.$class;
            $paySystem = $class::newInstance($userCurrent, $bill, $cost, $em, $this->get('service_container'));
            $html .= $paySystem->toc();
        }
        return new Response ($html);
    }
    public function chooseSourcesAction($bill_id, $source_id)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $bill_model = new UsersBillsModel($em);
        $bill = $bill_model->findByPK($bill_id);
        $bill->setSourceId($source_id);
        $bill_model->create($bill);
        return new RedirectResponse($this->generateUrl('users_bills_show'));
    }
    public function confirmAction($id, $value)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $bill_model = new UsersBillsModel($em);
        $user_model = new UsersModel($em);
        $order_model = new OrdersModel($em);
        $orderShared_model = new OrdersSharedModel($em);
        $bill = $bill_model->findByPK($id);
        $user = $user_model->findByPK($bill->getUserId());
        $bill->setIsPaid($value);
        $bill_model->create($bill);

        $totalTransaction_model = new UsersTotalTransactionsModel($em);
        $totalTransaction = $totalTransaction_model->findByUserId($bill->getUserId());
        $temp = $totalTransaction->getMoney();
        $orderShared = $orderShared_model->findByOrderId($bill->getOrderId());
        $order = $order_model->findByPK($bill->getOrderId());
        
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $userCurrent = $this->get('session')->get('user');
        if ($value == '0')//отмена оплаты
        {
            $totalTransaction->setMoney($temp - $bill->getMoney());
            
            if (!$bill->getIsReal())
            {
                $acl = $this->get('acl');
                $acl->removePermissionsForOne($bill, $user);
                $acl->removePermissionsForAllAdmins($bill);
                $bill_model->removeByPK($id);
                return new RedirectResponse($this->generateUrl('users_bills_show'));
            }
            else
            {
                $acl = $this->get('acl');
                $rem_bills = $bill_model->findNotReal($bill->getOrderId());
                foreach($rem_bills as $rem_bill)
                {
                    $transaction = new usersTransactions();
                    $transaction->setMoney($rem_bill->getMoney());
                    $transaction->setOrderId($rem_bill->getOrderId());
                    $transaction->setUserId($rem_bill->getUserId());
                    $transaction->setBillId($rem_bill->getId());
                    $transaction->setIsAdding('0');
                    $transaction->setIsRegular('0');
                    $transaction_model->create($transaction);

                    $totalTransaction = $totalTransaction_model->findByUserId($rem_bill->getUserId());
                    $totalTransaction->setMoney($totalTransaction->getMoney() - $rem_bill->getMoney());
                    $totalTransaction_model->create($totalTransaction);

                    $acl->removePermissionsForOne($rem_bill, $user);
                    $acl->removePermissionsForAllAdmins($rem_bill);
                    $bill_model->removeByPK($rem_bill->getId());
                }
                
                if (isset($order) && $order->isVps())
                {
                    $group_model = new OrdersIpTableModel($em);
                    $groups = $group_model->findAll();
                    foreach ($groups as $group)
                    {
                        $ips = $ip_model->findByAccountAndType($orderVps->getName(), 2);
                        foreach ($ips as $ip)
                        {
                            $ip->setTypeId(0);
                            $ip->setAccount('');
                            $ip_model->create($ip);
                        }
                    }
                }
            }
        }
        else if ($value == '1')//подтверждение оплаты
        {
            $totalTransaction->setMoney($temp + $bill->getMoney());
            if ( (isset($order)) && ($bill->getType() == '1') )
            {
                if (!$order->isVps())
                {
                    $jabber = $this->get('jabber');
                    if ($jabber->check())
                    {
                        $id = $jabber->sendMessage(16, array('password' => $user->getPassword()));
                        $result = $jabber->waitMessage($id);
                        $res = explode("_", $result['0']);
                        $orderShared->setUnixWorker($res['0']);
                        $orderShared->setUnixLogin($res['1']);
                    }
                    $orderShared_model->simple_update($orderShared);
                }
                else
                {
                    $group_model = new OrdersIpTableModel($em);
                    $ip_model = new OrdersIpModel($em);
                    $orderVps_model = new OrdersVpsModel($em);
                    $groups = $group_model->findAll();
                    $orderVps = $orderVps_model->findByOrderId($order->getId());
                    $count = $orderVps->getDedIpCount();

                    while ($count > 0)
                    {
                        foreach ($groups as $group)
                        {
                            $inserted = false;
                            $free_ips = $ip_model->findFree($group->getId());
                            $free_ip = $free_ips[0];
                            if (isset($free_ip))
                            {
                                if ($count > 0)
                                {
                                    $free_ip->setTypeId('2');
                                    $free_ip->setAccount($orderVps->getName());
                                    $ip_model->create($free_ip);
                                    $inserted = true;
                                    $count--;
                                }
                            }
                        }
                        if (!$inserted)
                            break;//+отсылать сообщение админу
                    }
                }
                
                $bonus_model = new BonusesModel($em);
                $bonusTable_model = new BonusesTableModel($em);
                $bonuses = $bonus_model->findByActive('1');
                foreach($bonuses as $bonus)
                {
                    /*if ($bill->getMoney() > $bonus->getSum())
                    {
                        $add_money = $bill->getMoney() * $bonus->getPercent() / 100;

                        $bill_bonus = new usersBills();
                        $bill_bonus->setMoney($add_money);
                        $bill_bonus->setIsReal('0');
                        $bill_bonus->setIsPaid('1');
                        $bill_bonus->setSourceId('0');
                        $bill_bonus->setUserId($user->getId());
                        $bill_bonus->setCurrencyId('1');
                        if (isset($order))
                            $bill_bonus->setOrderId($order->getId());
                        else
                            $bill_bonus->setOrderId('0');
                        $bill_bonus->setType('6');
                        $bill_model->create($bill_bonus);

                        $acl = $this->get('acl');
                        $acl->createPermissionsForOne($bill_bonus, $user, MaskBuilder::MASK_OWNER);
                        $acl->createPermissionsForAllAdmins($bill_bonus);

                        $transaction = new usersTransactions();
                        $transaction->setMoney($add_money);
                        $transaction->setOrderId($bill_bonus->getOrderId());
                        $transaction->setUserId($bill_bonus->getUserId());
                        $transaction->setBillId($bill_bonus->getId());
                        $transaction->setIsAdding('1');
                        $transaction->setIsRegular('0');
                        $transaction_model->create($transaction);

                        $totalTransaction = $totalTransaction_model->findByUserId($bill_bonus->getUserId());
                        $totalTransaction->setMoney($totalTransaction->getMoney() + $add_money);
                        $totalTransaction_model->create($totalTransaction);

                        if ($bonus->getType() == 1)
                        {
                            $bonusTable = new bonusesTable();
                            $bonusTable->setBonusId($bonus->getId());
                            $bonusTable->setIsActive('1');
                            $bonusTable->setUserId($bill_bonus->getUserId());
                            $bonusTable_model->create($bonusTable);
                        }
                    }*/
                }
            }
            if ($bill->getType() == '4')
            {
                if (isset($order))
                {
                    $orderShared_model = new OrdersSharedModel($em);
                    $orderShared = $orderShared_model->findByOrderId($order->getId());
                    $unix_login = $orderShared->getUnixLogin();
                }
                else
                    $unix_login = "0";

                $jabber = $this->get('jabber');
                if (!$jabber->check())
                    return new Response('jabber error');

                $domain_model = new DomainsModel($em);
                $domain = $domain_model->findByPK($bill->getDomainId());
                $check_domain = $this->get('check_domain');
                $check_domain->init($domain->getName());
                $dns_string = '';
                $dns_model = new DomainsDnsModel($em);           
                $dnss = $dns_model->findByDomainId($bill->getDomainId());
                foreach($dnss as $dns)
                {
                    $dns_string .= $dns->getName().' '.$dns->getType().' '.$dns->getValue();
                    if ($dns->getType() == "NS")
                        $dns_string .= "\n";
                }
                $id = $jabber->sendMessage(33, array('domain' => '"'.$unix_login.'|'.$check_domain->getDomain().'"', 'dns_string' => '"'.$dns_string.'"'));

                $domain->setMessageId($id);
                $domain_model->create($domain);    
            }
            if ($bill->getType() == '7')
            {
                $orderShared_model = new OrdersSharedModel($em);
                $orderShared = $orderShared_model->findByOrderId($order->getId());
                $unix_login = $orderShared->getUnixLogin();
                $group_model = new OrdersIpTableModel($em);
                $ip_model = new OrdersIpModel($em);
                $groups = $group_model->findAll();
                $count = $bill->getPeriod();
                $suc_inserted = 0;
                while ($count > 0)
                {
                    foreach ($groups as $group)
                    {
                        $inserted = false;
                        $free_ips = $ip_model->findFree($group->getId());
                        $free_ip = $free_ips[0];
                        if (isset($free_ip))
                        {
                            if ($count > 0)
                            {
                                $free_ip->setTypeId('3');
                                $free_ip->setAccount($unix_login);
                                $free_ip->setIsActive('1');
                                $ip_model->create($free_ip);
                                $inserted = true;
                                $suc_inserted++;
                                $count--;
                            }
                        }
                    }
                    if (!$inserted)
                        break;//+отсылать сообщение админу
                }
            }  
        }
        $totalTransaction_model->create($totalTransaction);

        if ($userCurrent->isAdmin())
        {
            $log_model = new UsersAdminLogsModel($em);
            $log = new usersAdminLogs();
            $log->setAdminId($userCurrent->getId());
            $log->setPageId('3');//страница счета
            $log->setObjectId($id);//изменяемый объект
            $log->setActionTypeId('4');//потверждение оплаты
            $log_model->create($log);
            return new RedirectResponse($this->generateUrl('users_bills_show'));
        }
        else
        {
            $log_model = new UsersLogsModel($em);
            $log = new usersLogs();
            $log->setUserId($userCurrent->getId());
            $log->setOrderId($bill->getOrderId());
            $log->setActionTypeId('8');//потверждение оплаты
            $log_model->create($log);
            return new Response('ok');
        }
    }
    public function addAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $bill_model = new UsersBillsModel($em);
        $bill = new usersBills();
        //$bill_model->create($bill->initDefaultEntity());
        //return new RedirectResponse($this->generateUrl('users_bills_show'));//создание по умолчанию
        $form = $this->createForm(new UsersBillsForm, $bill);

        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if ($form->isValid())
            {
                $securityContext = $this->container->get('security.context');
                $userCurrent = $securityContext->getToken()->getUser();

                $bill->setIsReal('1');
                $bill->setIsPaid('0');
                $bill->setSourceId('0');
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $bill->setUserId($this->get('session')->get('user')->getId());
                else
                    $bill->setUserId($userCurrent->getId());
                $bill->setCurrencyId('1');
                $bill->setOrderId('0');
                $bill->setType('3');
                $bill_model->create($bill);

                $acl = $this->get('acl');
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $acl->createPermissionsForOne($bill, $this->get('session')->get('user'), MaskBuilder::MASK_OWNER);
                else
                    $acl->createPermissionsForOne($bill, $userCurrent, MaskBuilder::MASK_OWNER);
                $acl->createPermissionsForAllAdmins($bill);

                $log_model = new UsersLogsModel($em);
                $log = new usersLogs();
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $log->setUserId($this->get('session')->get('user')->getId());
                else
                    $log->setUserId($userCurrent->getId());
                $log->setActionTypeId('1');//добавление счета
                $log->setOrderId('0');
                $log_model->create($log);
                return new RedirectResponse($this->generateUrl('users_bills_show'));
            }
        }
        return $this->render('BillingBundle:UsersBills:create.html.twig', array('form' => $form->createView()));
    }
    public function removeAction($id)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $bill_model = new UsersBillsModel($em);
        $bill = $bill_model->findByPK($id);

        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        $acl = $this->get('acl');
        $acl->checkPermissions($bill, 'DELETE');
        $acl->removePermissionsForOne($bill, $userCurrent);
        $acl->removePermissionsForAllAdmins($bill);

        $bill_model->removeByPK($id);
        //+ удалять все зависимое
        $log_model = new UsersAdminLogsModel($em);
        $log = new usersAdminLogs();
        $log->setAdminId($userCurrent->getId());
        $log->setPageId('3');//страница счета
        $log->setObjectId($id);//изменяемый объект
        $log->setActionTypeId('3');//удаление счета
        $log_model->create($log);
        return new RedirectResponse($this->generateUrl('users_bills_show'));
    }
}